package com.hzit.servlet;

import cn.hutool.core.util.StrUtil;
import com.hzit.entity.R;
import com.hzit.entity.Student;
import com.hzit.service.StudentService;
import com.hzit.util.ResponseUtil;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {
	private StudentService studentSerice;
	@Override
	public void init() throws ServletException {
		//1. 从tomcat容器中得到spring容器
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		//2. 从spring容器中得到bean
		studentSerice = wac.getBean(StudentService.class);
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1. 处理响应编码
		resp.setContentType("application/json;charset=utf8");
		//2. 得到请求参数
		String cmd = req.getParameter("cmd");
		//3. 根据参数的值，调用不同的方法
		if(StrUtil.isNotBlank(cmd)){
			if("list".equals(cmd)){     // 列表学生
				list(req,resp);
			}
		}
	}
	private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1. 查询所有学生
		List<Student> students = studentSerice.findAll();
		//2. 构造r对象
		R<List<Student>> ok = R.ok(students);
		//3. 转换为字符串再输出
		ResponseUtil.out(resp,ok);
	}
}
